package cn.xawl.gulimall.cart.controller;

import cn.xawl.gulimall.cart.service.CartService;
import cn.xawl.gulimall.cart.vo.Cart;
import cn.xawl.gulimall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author lh
 * @create 2020-11-02 11:19
 **/
@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("/cart.html")
    public String cartList(Model model) {

        //获取购物车信息，渲染到购物车页面
        Cart cart = cartService.userCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    /**
     * 添加购物车的真是操作。
     * 该接口一直调用会导致商品频繁添加，因此重定向到另一个页面后再跳转到添加成功页面可以防止重复调用接口
     * @param skuId 添加的商品id
     * @param count 添加的商品数量
     * @param redirectAttributes 向重定向的url添加商品id
     * @return 重定向到 /addToCart.html
     */
    @GetMapping("/gate.action")
    public String gate(@RequestParam("skuId") Long skuId, @RequestParam("count") Integer count, RedirectAttributes redirectAttributes) {
        cartService.addToCart(skuId, count);
//        model.addAttribute("item", cartItem);
        redirectAttributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.gulimall.com/addToCart.html";
    }

    @GetMapping("/addToCart.html")
    public String addToCart(@RequestParam("skuId") Long skuId, Model model) {
        CartItem cartItem = cartService.getCartItems(skuId);
        model.addAttribute("item", cartItem);
        return "success";
    }

    /**
     * 修改对应sku的选择属性
     * @param skuId skuId
     * @param check 是否被选择 -1：未选择；-2：选择
     * @return 跳转路径
     */
    @GetMapping("/check.action")
    public String cartCheck(String skuId, Integer check) {
        cartService.cartItemChange(skuId, check);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/count.action")
    public String cartCount(String skuId, Integer count) {
        cartService.cartItemChange(skuId, count);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/delete.action")
    public String cartDelete(String skuId) {
        cartService.cartItemChange(skuId, null);
        return "redirect:http://cart.gulimall.com/cart.html";
    }



}
